package com.example.sunran.servlet;

import javax.naming.Name;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

public class DownloadFileServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String path =  req.getParameter("type");
        String fileName = req.getParameter("name");

        File file = null;
        switch (path){
            case "video":
                file = new File("./UploadFile/Video/"+ fileName);
                break;
            case "image":
                file = new File("./UploadFile/Image/"+ fileName);
                break;
            case "doc":
                file = new File("./UploadFile/Doc/"+ fileName);
                break;
            case "other":
                file = new File("./UploadFile/Other/"+ fileName);
                break;
        }
        FileInputStream fis = new FileInputStream(file);
//        resp.setContentType("application/force-download");
        resp.setContentType("application/x-download");
        resp.setHeader("Content-Length",String.valueOf(fis.available()));
        resp.setHeader("content-disposition","attachment;filename=\""+fileName+"\"");
        OutputStream os = resp.getOutputStream();
        byte[] bytes = new byte[fis.available()];


        os.write(bytes);
        os.flush();
        os.close();
    }
}
